package top.ucat.boots.example.elasticsearch.controller;

import lombok.AllArgsConstructor;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import top.ucat.boots.common.result.Result;
import top.ucat.boots.common.result.SystemResult;

import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


/**
 * @Auther: Jun
 * @Date: 2019/11/18 10:21
 * @Description:
 */
@RestController
@RequestMapping("test")
public class TestController {

//    @Autowired
//    ElasticsearchTemplate elasticsearchTemplate;

    @Autowired
    private RestHighLevelClient restHighLevelClient;

    private SearchRequest buildSearchRequest(String index, String type) {
        SearchRequest searchRequest = new SearchRequest();
        searchRequest.indices(index);
        searchRequest.types(type);
        return searchRequest;
    }

    @GetMapping
    public Result test1() throws Exception {

//        NativeSearchQuery build = new NativeSearchQueryBuilder()
//                .withQuery(matchQueryBuilder)
//                .build();
//        NativeSearchQuery build1 = new NativeSearchQueryBuilder().build();
//        List<SystemLog> systemLogs = elasticsearchTemplate.queryForList(build1, SystemLog.class);


        SearchRequest searchRequest = buildSearchRequest("system_log", "_doc");
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
        searchSourceBuilder.query(QueryBuilders.matchAllQuery());
        searchRequest.source(searchSourceBuilder);
        SearchResponse rp =
                restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);
        SearchHit[] hits = rp.getHits().getHits();


        List<Map<String, Object>> collect = Arrays.stream(rp.getHits().getHits()).map(b -> {
            return b.getSourceAsMap();
        }).collect(Collectors.toList());

        return SystemResult.OK.getResult(collect);
    }

}
